package com.uyii.virtualthread.demos.web;

import org.springframework.stereotype.Service;
import java.util.concurrent.*;

@Service
public class PerformanceTestService {

    private static final int TASK_COUNT = 100_000; // 任务数量

    // 测试传统线程池性能
    public void testTraditionalThreads() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(100); // 创建固定大小的线程池
        long startTime = System.nanoTime(); // 获取当前时间
        for (int i = 0; i < TASK_COUNT; i++) {
            executorService.submit(() -> {
                try {
                    // 模拟 I/O 操作
                    Thread.sleep(100);  // 阻塞 100 毫秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        executorService.shutdown(); // 关闭线程池
        executorService.awaitTermination(1, TimeUnit.MINUTES); // 等待所有任务完成
        long endTime = System.nanoTime(); // 获取结束时间
        System.out.println("传统线程池执行时间：" + (endTime - startTime) / 1_000_000 + " ms");
    }

    // 测试虚拟线程池性能
    public void testVirtualThreads() {
        ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor(); // 创建虚拟线程池
        long startTime = System.nanoTime(); // 获取当前时间
        for (int i = 0; i < TASK_COUNT; i++) {
            executorService.submit(() -> {
                try {
                    // 模拟 I/O 操作
                    Thread.sleep(100);  // 阻塞 100 毫秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        executorService.shutdown(); // 关闭线程池
        while (!executorService.isTerminated()) {
            // 等待所有任务完成
        }
        long endTime = System.nanoTime(); // 获取结束时间
        System.out.println("虚拟线程池执行时间：" + (endTime - startTime) / 1_000_000 + " ms");
    }
}